﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;

namespace 发送邮件
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //输入检验
        private bool check()
        {
            if (textBox1.Text.Trim().IndexOf('@') <= 0)
            {
                MessageBox.Show("发件人邮箱格式不正确！\n形如：sci@163.com");
                return false;
            }

            if (textBox2.Text.Equals(""))
            {
                MessageBox.Show("请输入发件人密码");
                return false;
            }

            if (textBox3.Text.Trim().IndexOf('@') <= 0)
            {
                MessageBox.Show("收件人邮箱格式不正确！\n形如：sci@163.com\n多个收件人使用';'分隔");
                return false;
            }

            //避免向我发送无用邮件
            if (textBox3.Text.Equals("scimence@qq.com"))
            {
                if (textBox4.Text.Equals("") && textBox5.Text.Equals("") && richTextBox1.Text.Equals(""))
                {
                    MessageBox.Show("标题、内容、附件均为空的邮件\n将不发送给作者");
                    return false;
                }
            }

            if (textBox4.Text.Equals(""))//主题设置
            {
                textBox4.Text = DateTime.Now.ToString();
            }

            return true;
        }

        //发送邮件
        private void button1_Click(object sender, EventArgs e)
        {
            if (!check()) return;        //输入信息格式不正确

            if (sendEmail(textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, richTextBox1.Text, textBox5.Text))
                MessageBox.Show("邮件成功发送");
            else
                MessageBox.Show("邮件发送失败\n请确保您的账号密码正确\n且在邮箱的设置中已开通smtp服务");
        }

        //分别向所有收件人单独发送邮件
        private void button3_Click(object sender, EventArgs e)
        {
            if (!check()) return;           //输入信息格式不正确

            string to = textBox3.Text;
            if (to.IndexOf(';') > 0)        //添加收件人
            {
                foreach (string str in to.Split(';'))
                {
                    if (!sendEmail(textBox1.Text, textBox2.Text, str, textBox4.Text, richTextBox1.Text, textBox5.Text))
                        MessageBox.Show("向" + str + "邮件发送失败");
                }
            }
            else if (!to.Equals(""))
                if (!sendEmail(textBox1.Text, textBox2.Text, to, textBox4.Text, richTextBox1.Text, textBox5.Text))
                    MessageBox.Show("向" + to + "邮件发送失败");

            MessageBox.Show("邮件发送成功");
        }

        //发送邮件
        private bool sendEmail(string from, string psw, string to, string subject, string body, string attach)
        {   //使用时先添加引用 using System.Net.Mail;
            //设置smtp
            SmtpClient client = new System.Net.Mail.SmtpClient();
            client.Host = "smtp." + from.Substring(from.IndexOf('@') + 1);          //根据用户账号设置邮件服务器
            client.Credentials = new System.Net.NetworkCredential(from, psw);       //设置账户密码

            //设置邮件
            MailMessage message = new MailMessage();
            message.From = new MailAddress(from);
            message.Subject = subject;
            message.Body = body;

            if (to.IndexOf(';') > 0)        //添加收件人
            {
                foreach (string str in to.Split(';'))
                    message.To.Add(str);
            }
            else if (!to.Equals(""))
                message.To.Add(to);

            if (attach.IndexOf(';') > 0)    //添加附件
            {
                foreach (string str in attach.Split(';'))
                        message.Attachments.Add(new Attachment(str));
            }
            else if (!attach.Equals("")) 
                message.Attachments.Add(new Attachment(attach));

            try { client.Send(message); return true; }
            catch (Exception)
            { return false; }
        }

        //添加附件
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;
            if (dialog.ShowDialog()== DialogResult.OK)
            {
                foreach(string str in dialog.FileNames)
                    if (textBox5.Text.Equals("")) textBox5.Text = str;
                    else textBox5.Text += ";" + str;
            }
        }

        //记住密码账号 和 不记住
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            //设置一个具有写权限的键 访问键注册表"HKEY_CURRENT_USER\Software"
            Microsoft.Win32.RegistryKey keyCur = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true);
            Microsoft.Win32.RegistryKey keySet = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\scimence\Email\Set", true);

            if (checkBox1.Checked)
            {   //键不存在时创建键,创建键"HKEY_CURRENT_USER\Software\scimence\Email\Set"
                if (keySet == null) keySet = keyCur.CreateSubKey(@"Scimence\Email\Set");                             

                //然后将用户名和密码作为键值存储到注册表中
                keySet.SetValue("邮箱", textBox1.Text);
                keySet.SetValue("密码", textBox2.Text);
            }
            else if (keySet != null) keyCur.DeleteSubKeyTree(@"scimence\Email\Set");         //删除所有的设置信息
        }

        //此函数用于从注册表中获取初始化时的软件设置，设置用户名和密码
        private void RegistrySet()
        {
            Microsoft.Win32.RegistryKey keySet = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\scimence\Email\Set", true);
            //设置一个具有写权限的键 访问键注册表"HKEY_CURRENT_USER\Software"
            if (keySet != null)
            {
                checkBox1.Checked = true;
                textBox1.Text = Convert.ToString(keySet.GetValue("邮箱", ""));  //从注册表中获取用户名的值，显示在文本框中
                textBox2.Text = Convert.ToString(keySet.GetValue("密码", ""));    //获取密码
            }
            else checkBox1.Checked = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            RegistrySet(); //获取保存在注册表中的用户设置
        }

        //文件拖进
        private void textBox5_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))    //判断拖来的是否是文件
                e.Effect = DragDropEffects.Link;                //是则将拖动源中的数据连接到控件
            else e.Effect = DragDropEffects.None; 
        }

        //放下文件
        private void textBox5_DragDrop(object sender, DragEventArgs e)
        {
            Array file = (System.Array)e.Data.GetData(DataFormats.FileDrop);//将拖来的数据转化为数组存储

            int len = file.Length;
            for (int i = 0; i < len;i++ )
                if (textBox5.Text.Equals("")) textBox5.Text = file.GetValue(i).ToString();
                else textBox5.Text += ";" + file.GetValue(i).ToString();
        }

        private void textBox3_DoubleClick(object sender, EventArgs e)
        {
            textBox3.Text = "scimence@qq.com";
        }

        private void toolTip1_Popup(object sender, PopupEventArgs e)
        {

        }
    }
}

        ////邮件实例(测试通过)
        //private void button3_Click(object sender, EventArgs e)
        //{
        //    //System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        //    //client.Host = "smtp.163.com";//使用163的SMTP服务器发送邮件
        //    //client.UseDefaultCredentials = true;
        //    //client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
        //    //client.Credentials = new System.Net.NetworkCredential("scimence", "wz74153697895123");//163的SMTP服务器需要用163邮箱的用户名和密码作认证，如果没有需要去163申请个,
        //    ////这里假定你已经拥有了一个163邮箱的账户，用户名为abc，密码为*******
        //    //System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
        //    //Message.From = new System.Net.Mail.MailAddress("scimence@163.com");//这里需要注意，163似乎有规定发信人的邮箱地址必须是163的，而且发信人的邮箱用户名必须和上面SMTP服务器认证时的用户名相同
        //    ////因为上面用的用户名abc作SMTP服务器认证，所以这里发信人的邮箱地址也应该写为abc@163.com
        //    //Message.To.Add("scimence@qq.com");//将邮件发送给Gmail
        //    ////Message.To.Add("123456@qq.com");//将邮件发送给QQ邮箱
        //    //Message.Subject = "测试标体2";
        //    //Message.Body = "测试邮件体2";
        //    //Attachment file1 = new Attachment(@"D:\2.jpg");
        //    //Message.Attachments.Add(file1);
        //    //Message.SubjectEncoding = System.Text.Encoding.UTF8;
        //    //Message.BodyEncoding = System.Text.Encoding.UTF8;
        //    //Message.Priority = System.Net.Mail.MailPriority.High;
        //    //Message.IsBodyHtml = true;
        //    //client.Send(Message);
        //}